import json

from flask import request, jsonify, make_response
from flask_httpauth import HTTPTokenAuth
from plantmanagement import app, db
from plantmanagement.fun import Tools
from plantmanagement.controller.Users import UserController
from plantmanagement.controller.Plants import PlantController
from plantmanagement.controller.UserPlants import UserPlantController
from plantmanagement.controller.UserRecord import UserRecordController
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer, BadSignature, SignatureExpired

from plantmanagement import settings

from qiniu import Auth, put_data, etag

access_key = '56dCm9iUHoXC2uhl23vD2p1tjv65vHSGYOjWQv5u'
secret_key = '4_U6bZkP8kDB1i9n7LSZll8-G-WRQC39-lgImOnb'
q = Auth(access_key, secret_key)

auth = HTTPTokenAuth(scheme='JWT')


# 用户注册
@app.route('/reg')
def reg():
    '''
    nickname:用户昵称
    head:头像
    openid：用户微信id
    '''
    nickname = request.args.get('name')
    head = request.args.get('head')
    openid = request.args.get('openid')
    data = UserController.insert(head=head, nickname=nickname, openid=openid)
    return data


# 获取个人信息
@app.route('/userInfo')
# @auth.login_required
def userInfo():
    '''
    userid：用户id
    :return:
    '''
    userid = request.args.get('userid')
    data = UserController.queryUser(userid)
    print(data)
    return data


# 更改个人信息
@app.route('/editUserInfo')
def editUserInfo():
    userid = request.args.get('userid')
    head = request.args.get('head') if request.args.get('head') else None
    nickname = request.args.get('nickname') if request.args.get('nickname') else None
    data = UserController.editUserInfo(userid=userid, head=head, nickname=nickname)
    return data


# 添加植物信息
@app.route('/addPlant')
def addPlant():
    plantname = request.args.get('plantname')
    introduce = request.args.get('introduce')
    src = request.args.get('src')
    data = PlantController.add(plantname=plantname, introduce=introduce, src=src)
    return data


# 删除植物信息
@app.route('/delPlant')
def delPlant():
    plantid = request.args.get('plantid')
    data = PlantController.dels(plantid=plantid)
    return data


# 编辑植物
@app.route('/editPlant')
def editPlant():
    plantid = request.args.get('plantid')
    plantname = request.args.get('plantname') if request.args.get('plantname') else None
    introduce = request.args.get('introduce') if request.args.get('introduce') else None
    src = request.args.get('src') if request.args.get('src') else None
    data = PlantController.edits(plantid=plantid, plantname=plantname, introduce=introduce, src=src)
    return data


# 用户添加植物
@app.route('/addPlants')
def addPlants():
    userid = request.args.get('userid')
    plantsrc = request.args.get('plantsrc')
    plantname = request.args.get('plantname')
    introduce=request.args.get('introduce')
    data = UserPlantController.addPlants(plantname=plantname, userid=userid,plantsrc=plantsrc,introduce=introduce)
    return jsonify(data)


# 获取用户所有植物
@app.route('/getUserPlantAll')
def getUserPlantAll():
    userid = request.args.get('userid')
    data = UserPlantController.allPlants(userid=userid)
    return {
        'code': 200,
        'data': data
    }


# 添加记录
@app.route('/pushRecord')
# @auth.login_required
def pushRecord():
    userid = request.args.get('userid')
    plantid = request.args.get('plantid')
    type = request.args.get('type')
    data = UserRecordController.pushRecord(userid=userid, plantid=plantid, type=type)
    print(data)
    return jsonify(data)


# 根据用户id和植物id获取记录
@app.route('/GetUserRecordList')
def sss():
    userid = request.args.get('userid')
    plantid = request.args.get('plantid')
    data = UserRecordController.GetUserRecordList(userid=userid, plantid=plantid)
    return {
        'code': 200,
        'data': data
    }

#根据用户id和植物id获取植物详情
@app.route('/getInfo')
def getinfo():
    userid = request.args.get('userid')
    plantid = request.args.get('plantid')
    data = UserRecordController.getPlantInfo(userid=userid,plantid=plantid)
    return jsonify(data)

# 所有请求之后钩子
# @app.after_request
# def afterRequest(response):
#     print('请求之后')
#     db.session.close()
#     return response


#  登录接口
@app.route('/login')
def login():
    openid = request.args.get('openid')
    # print(openid)
    if openid is None:
        return jsonify({
            'code': 200,
            'msg': 'openid为空'
        })
    else:
        s = UserRecordController.login(openid=openid)
        return jsonify(s)


@auth.verify_token
def verify_token(token):
    token = request.headers.get('token')
    s = Serializer(settings.SECRET_KEY)
    try:
        data = s.loads(token)
        print(data)
        return True
    except BadSignature:
        print('token不正确')
        return False
    except SignatureExpired:
        print('过期')
        return False


@auth.error_handler
def unauthorized():
    return make_response(jsonify({'code': 201, 'error': 'Token失效'}), 401)


@app.route('/r')
def index():
    data = Tools.r(datas='46.03904:124.81056')
    return data


@app.route('/upfile', methods=['POST'])
def upfile():
    bucket_name = 'fcjjxcx'
    localfile = request.files.get('file')
    key = localfile.filename
    policy = {
        'callbackUrl': 'http://fcjjxcx.s3-cn-south-1.qiniucs.com/',
        'callbackBody': 'filename=$(key)'
    }
    token = q.upload_token(bucket_name, key, 3600)

    ret, info = put_data(token, key, localfile.read())
    # res = ret
    # res['url']='http://qiniu.daoker.club/'+ret['key']
    data ={
        'code':200,
        'url':'http://qiniu.daoker.club/'+ret['key']
    }
    return data
@app.route('/getOpenid')
def getopenid():
    code = request.args.get('code')
    data = Tools.getOpenid(code)
    print(data)
    return data
